package com.myorg.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;
import org.primefaces.model.UploadedFile;

import com.myorg.util.email.EmailLoaderPst2Hdfs;

public class EmailTransformAndLoader {

	public static void transformAndLoad(UploadedFile file, final boolean compress) {
		String fileName = file.getFileName().toUpperCase();
		if (fileName.endsWith(".TXT")) {
			InputStream is = null;
			try {
				is = file.getInputstream();
				HdfsHelper hdfsHeler = new HdfsHelper();
				hdfsHeler.saveToHDFS(
						ConstantsToBeExternalized.DEFAULT_DIR_FILES_UPLOAD + "/"
								+ stripFileExtension(file.getFileName()) + ".txt", is);
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			} finally {
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
					}
				}
			}
		} else if (fileName.endsWith(".PST")) {
			InputStream is = null;
			try {
				is = file.getInputstream();
				File temp = File.createTempFile(file.getFileName(), ".tmp");
				temp.deleteOnExit();
				FileUtils.copyInputStreamToFile(is, temp);
				EmailLoaderPst2Hdfs.savePst2Hdfs(temp, ConstantsToBeExternalized.DEFAULT_DIR_FILES_UPLOAD + "/"
						+ stripFileExtension(file.getFileName()) + (compress ? "_pst.txt.gzip" : "_pst.txt"), compress);
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			} finally {
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
					}
				}
			}
		}
	}

	private static String stripFileExtension(String path) {
		int index = path.lastIndexOf(".");
		if (index != -1) {
			return path.substring(0, index);
		} else {
			return path;
		}
	}
}
